package com.mo.lib.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException

/**
 * @ author：mo
 * @ data：2021/11/18:9:18
 * @ 功能：
 */
val UTF8 = Charset.forName("UTF-8")

/** 拦截器：打印请求、响应信息*/
class LogInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response { // 打印请求报文
        val request: Request = chain.request()
        val requestBody = request.body
        var reqBody: String? = null
        val builder = StringBuilder()
        builder.append("   ")
//        val startTime = DateUtil.getMS()
        builder.append("\n发送请求-->>")
        val tag = request.tag()
        tag?.let {
            builder.append("\ntag         ：${tag}")
        }
        builder.append("\nurl          ：${request.url}")
        builder.append("\nmethod：${request.method}")
        builder.append("\nheaders：${request.headers.toString().replace("\n", "\t")}")
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset = UTF8
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }
            reqBody = buffer.readString(charset!!)
        }
        reqBody?.let {
            builder.append("\nparam   ：${reqBody!!.replace("&", "\t")}")
        }


        // 打印返回报文
        // 先执行请求，才能够获取报文
        val response: Response = chain.proceed(request)
        val responseBody = response.body
        var respBody: String? = null
        if (responseBody != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer()
            var charset = UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8)
                } catch (e: UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            respBody = buffer.clone().readString(charset!!)
        }
//        val endTime = DateUtil.getMS()
        builder.append("\n收到响应-->>")
        builder.append("\n收到响应-->>${response.code}")
        builder.append("\n耗        时：")
        builder.append("\n响应结果：$respBody")
        builder.append("\n ____")
        Log.i("x_log", builder.toString())
//        try {
//            val jsonObject = JSONObject(respBody)
//            val status = jsonObject.optInt("status")
//            when (status) {
//                0 -> {
//                    throw (ZeroException(jsonObject.optString("data")))
//                }
//                else -> {
//                    return response
//                }
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
            return response
//        }
    }
}

